#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "hal_bsp_sht20.h"
#include "hal_bsp_ssd1306.h"

void display_temperature_and_humidity(void)
{
    float temperature = 0, humidity = 0;
    char temp_str[20];
    char humi_str[20];

    // 初始化 OLED 屏幕
    if (SSD1306_Init() != 0) {
        printf("OLED initialization failed!\n");
        return;
    }

    // 初始化 SHT20 传感器
    SHT20_Init();

    while (1) {
        // 读取温湿度数据
        SHT20_ReadData(&temperature, &humidity);

        // 格式化数据
        snprintf(temp_str, sizeof(temp_str), "Temp: %.2f C", temperature);
        snprintf(humi_str, sizeof(humi_str), "Humi: %.2f %%", humidity);

        // 清屏
        SSD1306_CLS();

        // 显示温度数据
        SSD1306_ShowStr(0, 0, (uint8_t *)temp_str, 16);

        // 显示湿度数据
        SSD1306_ShowStr(0, 2, (uint8_t *)humi_str, 16);

        // 延时一段时间
        osDelay(2000); // 延时 2 秒
    }
}

static void main_task(void)
{
    osThreadAttr_t attr;
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024 * 4;
    attr.name = "display_task";
    attr.priority = 25;

    if (osThreadNew((osThreadFunc_t)display_temperature_and_humidity, NULL, &attr) == NULL) {
        printf("Failed to create display_task!\n");
    }
}

APP_FEATURE_INIT(main_task);